package com.shenjun.bank.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

@Component
public class HelloClientHandler extends ChannelInitializer<NioSocketChannel> {

    @Override
    protected void initChannel(NioSocketChannel channel) throws Exception {
        // 添加编码器（为消息添加长度前缀）
        channel.pipeline().addLast(new MessageToByteEncoder<String>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) {
                byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
                out.writeInt(bytes.length); // 写入4字节长度字段
                out.writeBytes(bytes);      // 写入实际数据
            }
        });
        // 响应解码器（与服务端解码器对称）
        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                1024, 0,
                4, 0, 4));
    }
}
